package com.artup.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.artup.common.Constants;
import com.artup.common.ResponseResult;
import com.artup.dao.RoleDao;
import com.artup.dao.UserRoleDao;
import com.artup.pojo.Role;
import com.artup.pojo.UserRole;
import com.artup.service.UserRoleService;
import com.artup.util.CommonUtils;
import com.artup.util.file.PropertiesUtils;

@Service( value = "userRoleService" )
@Transactional( readOnly = false )
public class UserRoleServiceImpl implements UserRoleService {
	private static final Logger LOGGER = LoggerFactory.getLogger(UserRoleServiceImpl.class);
	
	@Autowired
	private UserRoleDao userRoleDao;
	
	@Autowired
	private RoleDao roleDao;

	@Override
	public ResponseResult queryUserRoleById(long id) {
		LOGGER.info("id = " + id);
		ResponseResult responseResult = new ResponseResult();
		
		UserRole userRole = null;
		try {
			userRole = this.userRoleDao.selectUserRoleById(id);

			responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
			responseResult.setMessage("根据【ID】查询【用户角色】  - 成功。");
			responseResult.setData(userRole);
		} catch (Exception e) {
			LOGGER.error("根据【ID】查询【用户角色】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
			responseResult.setMessage("根据【ID】查询【用户角色】  - 成功。");
		}

		return responseResult;
	}

	/*@Override
	public ResponseResult queryUserRoleList(UserRole userRole) {
		ResponseResult responseResult = new ResponseResult();
		
		ObjectMapper mapper = new ObjectMapper();
		try {
			LOGGER.info("userRole = " + mapper.writeValueAsString(userRole));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		
		List<UserRole> userRoleList = null;
		try {
			userRoleList = this.userRoleDao.selectUserRoleList(userRole);
			
			responseResult.setStatus(1);
			responseResult.setMessage("模糊查询【用户角色列表】 - 成功。");
			responseResult.setData(userRoleList);
		} catch (Exception e) {
			LOGGER.error("模糊查询【用户角色列表】 - 失败！", e);
			
			responseResult.setStatus(2);
			responseResult.setMessage("模糊查询【用户角色列表】 - 失败！");
		}
		
		return responseResult;
	}*/

	@Override
	public ResponseResult queryUserRoleList(UserRole userRole) {
		LOGGER.info("userRole = " + JSONArray.toJSONString(userRole));
		
		// 1.定义返回的结果集
		ResponseResult responseResult = new ResponseResult();
		Map<String, Object> resultMap = new HashMap<String, Object>(); // 结果集

		// 3.模糊查询【用户角色】总记录数
		long totalCount = 0;
		try {
			totalCount = this.userRoleDao.selectUserRoleTotalCount(userRole);
		} catch (Exception e) {
			LOGGER.error("模糊查询【用户角色】总记录数 - 失败！", e);
		}

		resultMap.put("recordsTotal", totalCount);
		resultMap.put("recordsFiltered", totalCount);// 返回总条数

		if (0 < totalCount) {
			userRole.setOffset( (long) userRole.getPageIndex() ); // 设置分页的偏移量，即起始记录数

			// 4.模糊查询【用户角色】列表
			List<UserRole> userRoleList = null;
			try {
				userRoleList = this.userRoleDao.selectUserRoleList(userRole);
			} catch (Exception e) {
				LOGGER.error("模糊查询【用户角色】列表 - 失败！", e);

				responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
				responseResult.setMessage("模糊查询【用户角色】列表 - 失败！");
			}
			
			resultMap.put("data", userRoleList);// 返回的总数据
		} else {
			resultMap.put("data", new ArrayList<UserRole>()); // 返回的空数组
		}

		// 5.设置返回的结果集
		responseResult.setData(resultMap);
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("模糊查询【用户角色】列表 - 成功。");

		// 6.返回结果集
		return responseResult;
	}
	
	@Override
	public ResponseResult queryRoleList(Role role, long userId) {
		LOGGER.info("role = " + JSONArray.toJSONString(role) + ", userId = " + userId);
		
		// 1.定义返回的结果集
		ResponseResult responseResult = new ResponseResult();
		Map<String, Object> resultMap = new HashMap<String, Object>(); // 结果集

		// 3.模糊查询【角色】总记录数
		long totalCount = 0;
		try {
			totalCount = this.roleDao.selectRoleTotalCount(role);
		} catch (Exception e) {
			LOGGER.error("模糊查询【角色】总记录数 - 失败！", e);
		}

		resultMap.put("recordsTotal", totalCount);
		resultMap.put("recordsFiltered", totalCount);// 返回总条数

		if (0 < totalCount) {
			role.setOffset( (long) role.getPageIndex() ); // 设置分页的偏移量，即起始记录数

			// 4.模糊查询【角色】列表
			List<Role> roleList = null;
			try {
				roleList = this.roleDao.selectRoleList(role);
			} catch (Exception e) {
				LOGGER.error("模糊查询【角色】列表 - 失败！", e);
			}
			
			List<UserRole> selectedUserRoleList = null;
			try {
				selectedUserRoleList = this.userRoleDao.selectValidUserRoleListByUserId(userId);
			} catch (Exception e) {
				LOGGER.error("根据【用户ID】查询【用户角色】列表 - 失败！", e);

				responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
				responseResult.setMessage("根据【用户ID】查询【用户角色】列表 - 失败！");
			}
			
			if(CommonUtils.isNotEmpty(roleList)) {
				for(Role roleTemp : roleList) {
					if(null == roleTemp) {
						continue;
					}

					boolean isHaved = false;	// 是否有隶属的角色
					
					if(CommonUtils.isNotEmpty(selectedUserRoleList)) {
						for(UserRole roleBelongUser : selectedUserRoleList) {
							if(null == roleBelongUser) {
								continue;
							}
							
							if(roleTemp.getId() == roleBelongUser.getRoleId()) {
								isHaved = true;
							} 
						}
					}
					
					if(isHaved) {
						roleTemp.setIsBelong((byte) 1);
					} else {
						roleTemp.setIsBelong((byte) 2);
					}
				}
			}
			
			resultMap.put("data", roleList);// 返回的总数据
		} else {
			resultMap.put("data", new ArrayList<Role>()); // 返回的空数组
		}

		// 5.设置返回的结果集
		responseResult.setData(resultMap);
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("模糊查询【角色】列表 - 成功。");

		// 6.返回结果集
		return responseResult;
	}

	@Override
	public ResponseResult queryUserRoleListByUserId( long userId ) {
		LOGGER.info("userId = " + userId);
		
		ResponseResult responseResult = new ResponseResult();
		
		List<UserRole> userRoleList = null;
		try {
			userRoleList = this.userRoleDao.selectValidUserRoleListByUserId(userId);
		} catch (Exception e) {
			LOGGER.error("根据【用户ID】查询有效的【用户角色】列表 - 失败！", e);
		}
		
		responseResult.setData(userRoleList);
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("根据【用户ID】查询有效的【用户角色】列表 - 成功。");
		
		return responseResult;
	}

	@Override
	public ResponseResult saveUserRole(UserRole userRole) {
		LOGGER.info("userRole = " + JSONObject.toJSONString(userRole));
		
		ResponseResult responseResult = new ResponseResult();
		
		if(null != userRole) {
			try {
				this.userRoleDao.insertUserRole(userRole);
				
				responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
				responseResult.setMessage("保存【用户角色】 - 成功。");
			} catch (Exception e) {
				LOGGER.error("保存【用户角色】 - 失败！", e);
				
				responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
				responseResult.setMessage("保存【用户角色】 - 失败！");
			}
		}
		
		return responseResult;
	}
	
	@Override
	public ResponseResult updateUserRoleById(UserRole userRole) {
		LOGGER.info("userRole = " + JSONObject.toJSONString(userRole));
		ResponseResult responseResult = new ResponseResult();
		
		if(null != userRole) {
			try {
				this.userRoleDao.updateUserRoleById(userRole);
				
				responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
				responseResult.setMessage("更新【用户角色】 - 成功。");
			} catch (Exception e) {
				LOGGER.error("根据【ID】更新【用户角色】 - 失败！", e);
				
				responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
				responseResult.setMessage("更新【用户角色】 - 失败！");
			}
		}
		
		return responseResult;
	}
	
	@Override
	public ResponseResult updateUserRoleInvalidById(Long id, Long userId) {
		LOGGER.info("id = " + id + ", userId = " + userId);
		ResponseResult responseResult = new ResponseResult();
		
		try {
			this.userRoleDao.updateUserRoleInvalidById(id, userId);
		} catch (Exception e) {
			LOGGER.error("根据【ID】更新【用户角色】为无效的  - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("删除【角色】 - 失败！");
		}
		
		List<UserRole> userRoleList = null;
		try {
			userRoleList = this.userRoleDao.selectValidUserRoleListByUserId(userId);
		} catch (Exception e) {
			LOGGER.error("根据【用户ID】查询有效的【用户角色】列表 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("更新【用户角色】 - 失败！");
		}
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("删除【用户角色】 - 成功。");
		responseResult.setData(userRoleList);
		
		return responseResult;
	}

	@Override
	public ResponseResult updateUserRoleByUserId(long userId, String roleIds) {
		LOGGER.info("userId = {}, roleIds = {}", userId, roleIds);
		ResponseResult responseResult = new ResponseResult();
		
		UserRole userRole = new UserRole();
		userRole.setUserId(userId);
		userRole.setIsValid((byte) 2);		// 置为“无效”
		userRole.setModifierId(1L);
		
		// 将该用户名下的全部的“用户角色”置为无效
		try {
			this.userRoleDao.updateUserRoleByUserId(userRole);
		} catch (Exception e) {
			LOGGER.error("根据【用户ID】更新【用户角色】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("更新【用户角色】 - 失败！");
		}
		
		if(StringUtils.isBlank(roleIds)) {
			responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
			responseResult.setMessage("更新【用户角色】 - 成功。");
			
			return responseResult;
		}
		
		List<UserRole> userRoleList_db = null;
		try {
			userRoleList_db = this.userRoleDao.selectUserRoleListByUserId(userRole.getUserId());
		} catch (Exception e) {
			LOGGER.error("根据【用户ID】查询【用户角色】列表 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("为用户分配角色 - 失败！");
		}
		
		List<UserRole> newUserRoleList = new ArrayList<UserRole>();		// 新增的【用户角色】
		List<UserRole> updateUserRoleList = new ArrayList<UserRole>();	// 更新的【用户角色】
		
		String roleIds_ [] = roleIds.split(",");
		long _roleIds [] = new long[roleIds_.length];	
		
		// 类型转换
		for(int index = 0; index < roleIds_.length; index++) {
			String roleId = roleIds_[index];
			if(StringUtils.isBlank(roleId)) {
				continue;
			}
			
			_roleIds[index] = Long.parseLong(roleIds_[index]);
			UserRole newUserRole = new UserRole();
			newUserRole.setUserId(userId);
			newUserRole.setRoleId(Long.parseLong(roleIds_[index]));
			newUserRole.setIsValid((byte) 1);
			newUserRole.setCreatorId(1L);
			newUserRole.setModifierId(1L);
			newUserRoleList.add(newUserRole);
		}

		// 全部新增
		if(CommonUtils.isEmpty(userRoleList_db)) {
			try {
				this.userRoleDao.batchInsertUserRole(newUserRoleList);
			} catch (Exception e) {
				LOGGER.error("保存【用户-角色】 - 失败！", e);
				
				responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
				responseResult.setMessage("更新【用户角色】 - 失败！");
			}
		} else {	// 一部分置为“有效”，一部新增
			newUserRoleList.clear();
			
			for(long roleId : _roleIds) {
				boolean isHaved = false;	// 是否已有此角色：true-是；false-否
				long userRoleId_db = 0L;
				
				for(UserRole userRole_db : userRoleList_db) {
					if(null == userRole_db) {
						continue;
					}
					
					if(userRole_db.getRoleId() == roleId) {
						isHaved = true;
						
						userRoleId_db = userRole_db.getId();
					}
				}
				
				if(isHaved) {	// 置为“有效”
					UserRole updateUserRole = new UserRole();
					updateUserRole.setId(userRoleId_db);
					updateUserRole.setIsValid((byte) 1);
					updateUserRole.setModifierId(1L);
					
					updateUserRoleList.add(updateUserRole);
				} else {	// 新增
					UserRole newUserRole = new UserRole();
					newUserRole.setUserId(userId);
					newUserRole.setRoleId(roleId);
					newUserRole.setIsValid((byte) 1);
					newUserRole.setCreatorId(1L);
					newUserRole.setModifierId(1L);
					
					newUserRoleList.add(newUserRole);
				}
			}
			
			if(CommonUtils.isNotEmpty(newUserRoleList)) {
				try {
					this.userRoleDao.batchInsertUserRole(newUserRoleList);
				} catch (Exception e) {
					LOGGER.error("批量保存【用户角色】 - 失败！", e);
					
					responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
					responseResult.setMessage("更新【用户角色】 - 失败！");
				}
			}
			
			if(CommonUtils.isNotEmpty(updateUserRoleList)) {
				try {
					this.userRoleDao.batchUpdateUserRoleById(updateUserRoleList);
				} catch (Exception e) {
					LOGGER.error("根据【ID】批量更新【用户角色】 - 失败！", e);
					
					responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
					responseResult.setMessage("更新【用户角色】 - 失败！");
				}
			}
		}
		
		List<UserRole> userRoleList = null;
		try {
			userRoleList = this.userRoleDao.selectValidUserRoleListByUserId(userId);
		} catch (Exception e) {
			LOGGER.error("根据【用户ID】查询有效的【用户角色】列表 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("更新【用户角色】 - 失败！");
		}
		
		responseResult.setData(userRoleList);
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("为用户分配角色 - 成功。");
		return responseResult;
	}

	@Override
	public ResponseResult deleteUserRoleById(long id) {
		LOGGER.info("id = " + id);
		ResponseResult responseResult = new ResponseResult();
		
		try {
			this.userRoleDao.deleteUserRoleById(id);
			
			responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
			responseResult.setMessage("删除【用户角色】 - 成功。");
		} catch (Exception e) {
			LOGGER.error("根据【ID】删除【用户角色】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("删除【用户角色】 - 失败！");
		}
		
		return responseResult;
	}
	
	@Override
	public ResponseResult queryRoleList(Role role, Long userId) {
		LOGGER.info("role = {}, userId = {}", JSONArray.toJSONString(role), userId);
		
		ResponseResult responseResult = new ResponseResult();

		long totalCount = 0;
		try {
			totalCount = this.roleDao.selectRoleTotalCount(role);
		} catch (Exception e) {
			LOGGER.error("模糊查询【角色】总记录数 - 失败！", e);
		}
		
		if(0 == totalCount) {
			responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
			responseResult.setMessage("无角色！");
			
			return responseResult;
		}

		Map<String, Object> resultMap = new HashMap<String, Object>();	// 结果集
		resultMap.put("totalCount", totalCount);
		
		if(null == role.getPageIndex() || 0 >= role.getPageIndex()) {
			role.setPageIndex(1);
		}
		if(null == role.getPageSize() || 0 >= role.getPageSize()) {
			role.setPageSize(Integer.valueOf(PropertiesUtils.getValue("pagination.pageSize")));
		}
		
		long offset = (role.getPageIndex() - 1) * role.getPageSize();
		role.setOffset(offset);		 // 设置分页的偏移量，即起始记录数

		// 模糊查询【角色】列表
		List<Role> roleList = null;
		try {
			roleList = this.roleDao.selectRoleList(role);
		} catch (Exception e) {
			LOGGER.error("模糊查询【角色】列表 - 失败！", e);
		}

		resultMap.put("roleList", roleList);
		
		if(null != userId && 0 < userId){
			List<UserRole> userRoleList = null;
			try {
				userRoleList = this.userRoleDao.selectValidUserRoleListByUserId(userId);
			} catch (Exception e) {
				LOGGER.error("根据【用户ID】查询有效的【用户角色】列表 - 失败！", e);
			}

			if(CommonUtils.isNotEmpty(userRoleList)) {
				resultMap.put("userRoleList", userRoleList);
			}
		}

		// 设置返回的结果集
		responseResult.setData(resultMap);
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("模糊查询【角色】列表 - 成功。");

		// 返回结果集
		return responseResult;
	}
}